import {
    Component,
    ViewChild,
    Injector,
    Output,
    EventEmitter,
    ViewEncapsulation,
    ElementRef
} from '@angular/core';
import { ModalDirective, TabsetComponent } from 'ngx-bootstrap';
import {
    TechRuleServiceProxy,
    TechRuleListDto,
    StockOperationLogListDto,
    OutStocksInput,
    BackStocksInput,
    LocationDto,
    LocationServiceProxy,
    CreateOrUpdateTechRuleInput
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';

import { finalize } from 'rxjs/operators';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import { EventManager } from '@angular/platform-browser';

@Component({
    selector: 'actionTechRuleModal',
    templateUrl: './action-techrule-modal.component.html',
    styleUrls: ['./action-techrule-modal.component.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class ActionTechRuleModalComponent extends AppComponentBase {
    @ViewChild('actionModal') modal: ModalDirective;
    @ViewChild('carDataTable') carDataTable: Table;
    @ViewChild('logDataTable') logDataTable: Table;
    @ViewChild('logPaginator') logPaginator: Paginator;
    @ViewChild('outDataTable') outDataTable: Table;
    @ViewChild('outPaginator') outPaginator: Paginator;
    @ViewChild('areaCombobox') areaCombobox: ElementRef;
    @ViewChild('shelfCombobox') shelfCombobox: ElementRef;
    @ViewChild('positionCombobox') positionCombobox: ElementRef;
    @ViewChild('tset') tset: TabsetComponent;
    primengTableHelper1 = new PrimengTableHelper();
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    areas = new Array<LocationDto>();
    shelfs = new Array<LocationDto>();
    positions = new Array<LocationDto>();
    locations: any[];
    hasLoadLocations = false;
    areaId = 0;
    shelfId = 0;
    positionId = 0;
    isUpdate: boolean;

    logFilterText = '';
    FilterText = '';
    scanFilterText = '';
    scanHisText = '';

    operationNames = ['', '入库', '借出', '归还', '报废', '追回'];
    title = '';
    type = 1;

    StockInfo = '';
    Remark = '';

    carTechRules = new Array<TechRuleListDto>();
    selectCarTechRules = new Array<TechRuleListDto>();
    techruleLogs = new Array<StockOperationLogListDto>();
    outtechrules = new Array<TechRuleListDto>();

    destroyListener: any;

    constructor(
        injector: Injector,
        private _techruleService: TechRuleServiceProxy,
        private _locationServiceProxy: LocationServiceProxy,
        private eventManager: EventManager
    ) {
        super(injector);
    }

    show(type: number): void {
        this.active = true;
        this.areaId = 0;
        this.shelfId = 0;
        this.positionId = 0;
        this.title = this.operationNames[type];
        this.type = type;
        this.tset.tabs[0].active = true;
        this.scanHisText = '';
        this._locationServiceProxy.getAreas()
            .subscribe(result => {
                this.areas = result.items;
                setTimeout(() => {
                    $(this.areaCombobox.nativeElement).selectpicker('refresh');
                    $(this.shelfCombobox.nativeElement).selectpicker('refresh');
                    $(this.positionCombobox.nativeElement).selectpicker('refresh');
                }, 0);
            });

        // 初始化 信息
        this.StockInfo = '';
        this.Remark = '';

        // 初始化 dtos
        this.carTechRules = new Array<TechRuleListDto>();
        this.selectCarTechRules = new Array<TechRuleListDto>();
        this.techruleLogs = new Array<StockOperationLogListDto>();
        this.outtechrules = new Array<TechRuleListDto>();

        this.getCarTechRules();

        this.getTechRuleLogs();
        if (this.type === 2) {
            this.getOutTechRules();
        }
    }

    scaninit() {
        let input = new CreateOrUpdateTechRuleInput();
        input.operation = this.type;
        input.codeID = this.scanFilterText;
        this.scanHisText = this.scanFilterText;
        //扫码选中
        if (this.carTechRules.find(c => c.techRuleInfo.fileCode === this.scanHisText)
            && !this.selectCarTechRules.find(s => s.techRuleInfo.fileCode === this.scanHisText)) {
            this.getCarTechRules();
        } else {
            this.primengTableHelper.showLoadingIndicator();
            this._techruleService.scanTechRule(input)
                .pipe(finalize(() => {
                    this.saving = false;
                    this.primengTableHelper.hideLoadingIndicator();
                }))
                .subscribe(() => {
                    this.notify.info('扫码成功');
                    this.getCarTechRules();
                    this.primengTableHelper.hideLoadingIndicator();
                });
        }
        setTimeout(() => {
            this.scanFilterText = '';
        }, 500);

    }

    getCarTechRules() {
        this._techruleService.getCarTechRules(this.type).subscribe(result => {
            this.carTechRules = result.items;
            if (this.carTechRules.find(c => c.techRuleInfo.fileCode === this.scanHisText)
                && !this.selectCarTechRules.find(s => s.techRuleInfo.fileCode === this.scanHisText)) {
                this.selectCarTechRules.push(this.carTechRules.find(c => c.techRuleInfo.fileCode === this.scanHisText));
            }
            this.modal.show();
        });
    }

    loadShelfs() {
        this.shelfId = 0;
        this.positionId = 0;

        this._locationServiceProxy.getShelvesByArea(this.areaId)
            .subscribe(result => {
                this.shelfs = result.items;
                setTimeout(() => {
                    $(this.shelfCombobox.nativeElement).selectpicker('refresh');
                }, 0);
            });
    }

    loadPositions() {
        this.positionId = 0;

        this._locationServiceProxy.getPositionsByShelf(this.shelfId)
            .subscribe(result => {
                this.positions = result.items;
                setTimeout(() => {
                    $(this.positionCombobox.nativeElement).selectpicker('refresh');
                }, 0);
            });
    }

    close(): void {
        this.active = false;
        this.modalSave.emit(null);
        this.modal.hide();
    }

    saveStocks() {
        if (this.type === 2 || this.type === 4 || this.type === 5) {
             this.outStocks();
        } else {
            this.backStocks();
        }
    }

    scan() {
        // this.saving = true;
        // this._techruleService.goCar("BE69BF8F-FAC4-4505-B90C-08D84EECCDE2", this.type)
        //   .pipe(
        //     finalize(() => {
        //       this.saving = false;
        //     })
        //   )
        //   .subscribe(() => {
        //     this.getCarTechRules();
        //     this.notify.success('加入成功');
        //   });
    }

    cancelStocks() {
        let ids = this.selectCarTechRules.map(el => {
            return el.id;
        });
        this.saving = true;
        this._techruleService
            .cancelCars(ids)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info('取消成功');
                this.close();
                this.modalSave.emit(null);
            });
    }

    outStocks() {
        const input = new OutStocksInput();
        input.ids = this.selectCarTechRules.map(el => {
            return el.id;
        });

        input.operation = this.type;
        input.outStockInfo = this.StockInfo;
        input.outRemark = this.Remark;

        this.saving = true;

        this._techruleService
            .outStocks(input)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info('出库成功');
                this.close();
                this.modalSave.emit(null);
            });
    }

    backStocks() {
        const input = new BackStocksInput();
        input.ids = this.selectCarTechRules.map(el => {
            return el.id;
        });

        input.backStockInfo = this.StockInfo;
        input.backRemark = this.Remark;
        input.positionId = this.positionId;
        this.saving = true;

        this._techruleService
            .backStocks(input)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info('入库成功');
                this.close();
                this.modalSave.emit(null);
            });
    }

    getTechRuleLogs(event?: LazyLoadEvent) {
        setTimeout(() => {
            if (this.primengTableHelper.shouldResetPaging(event)) {
                this.logPaginator.changePage(0);
                return;
            }

            if (this.type === 0) {
                return;
            }

            this.primengTableHelper.showLoadingIndicator();

            this._techruleService
                .getTechRuleLogs(
                    undefined,
                    this.logFilterText,
                    this.type,
                    this.primengTableHelper.getSorting(this.logDataTable),
                    this.primengTableHelper.getMaxResultCount(this.logPaginator, event),
                    this.primengTableHelper.getSkipCount(this.logPaginator, event)
                )
                .subscribe(result => {
                    this.primengTableHelper.totalRecordsCount = result.totalCount;
                    this.primengTableHelper.records = result.items;
                    this.primengTableHelper.hideLoadingIndicator();
                });

        }, 0);
    }

    getOutTechRules(event?: LazyLoadEvent) {
        setTimeout(() => {
            if (this.primengTableHelper1.shouldResetPaging(event)) {
                this.outPaginator.changePage(0);
                return;
            }

            if (this.type === 0) {
                return;
            }

            this.primengTableHelper1.showLoadingIndicator();

            this._techruleService
                .getOutTechRules(
                    this.FilterText,
                    this.type,
                    this.primengTableHelper1.getSorting(this.outDataTable),
                    this.primengTableHelper1.getMaxResultCount(this.outPaginator, event),
                    this.primengTableHelper1.getSkipCount(this.outPaginator, event)
                )
                .subscribe(result => {
                    this.primengTableHelper1.totalRecordsCount = result.totalCount;
                    this.primengTableHelper1.records = result.items;
                    this.primengTableHelper1.hideLoadingIndicator();
                });

        }, 0);
    }
}
